import 'dart:async';

import 'package:flutter/material.dart';
import '../demo/ui_demo.dart';
import '../demo/data_source/post.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../wonders/framework.dart';
class MyDemo extends StatelessWidget implements Demo {
  MyDemo(this.title);
  @override
  String title;
  @override
  Widget build(BuildContext context) {
    return new HomePage(
      title: this.title,
    );
  }
}

class HomePage extends StatelessWidget {
  String title;
  HomePage({this.title});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(this.title),
        actions: <Widget>[
          IconSource("http", "21"),
        ],
      ),
      //body:HttpDemo(),
      body: DioHttpDemo(),
    );
  }
}

class HttpDemo extends StatefulWidget {
  @override
  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  List<Post> posts;
  @override
  void initState() {
    super.initState();
  }

  Future<List<Post>> fetchPosts() async {
    List<Post> posts;
    BaseResp response =
        await HttpUtils().get("https://resources.ninghao.net/demo/posts.json");
    if (response.statusCode == 200) {
      print("body type:${response.data.runtimeType}");
      Map map = response.data;
      List list = map['posts'];
      return list.map((item) => Post.fromJson(item)).toList();
    } else {
      throw Exception('Failed to fetch posts.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder(
          future: fetchPosts(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            print("sanpshot type:${snapshot.data.runtimeType}");
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: Text("loading....."),
              );
            }
            return ListView(
              children: snapshot.data.map<Widget>((item) {
                return ListTile(
                  title: Text(item.title),
                  subtitle: Text(item.author),
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(item.imageUrl),
                  ),
                );
              }).toList(),
            );
          }),
    );
  }
}

class DioHttpDemo extends StatefulWidget {
  @override
  _DioHttpDemoState createState() => _DioHttpDemoState();
}

class _DioHttpDemoState extends State<DioHttpDemo> {
  List<ToutiaoModel> _list = [];
  bool _loaded=false;
  String _url =
      "https://www.toutiao.com/api/pc/feed/?category=__all__&utm_source=toutiao&widen=1&tadrequire=true";

  GlobalKey<EasyRefreshState> _easyRefreshKey =
  new GlobalKey<EasyRefreshState>();
  GlobalKey<RefreshHeaderState> _headerKey =
  new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey =
  new GlobalKey<RefreshFooterState>();


  @override
  void initState() {
    super.initState();
    refresh();
  }
//加载更多
  Future<void> loadMore() async {
    int millisecond = (DateTime.now().millisecondsSinceEpoch / 1000).floor();
    _url = "$_url&max_behot_time=$millisecond";
    await HttpUtils().get(_url).then((response) {
      if (response.statusCode == 200) {
        for (var value in response.data["data"]) {
          _list.add(ToutiaoModel(value["title"],
              imageUrl: value["image_url"]));
        }
        setState(() {});
      }
    });
  }
  //刷新当前页面
  Future<void> refresh() async {
    int millisecond = (DateTime.now().millisecondsSinceEpoch / 1000).floor();
    _url = "$_url&max_behot_time=$millisecond";
    _list.clear();
    await HttpUtils().get(_url).then((response) {
      if (response.statusCode == 200) {
        for (var value in response.data["data"]) {
          _list.add(ToutiaoModel(value["title"],
              imageUrl: value["image_url"]));
        }
        _loaded=true;
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if(!_loaded){
      return getLoadingWidget(context);
    }
    return EasyRefresh(
      key: _easyRefreshKey,
      onRefresh: refresh,
      loadMore: loadMore,
      refreshHeader: ClassicsHeader(
        key: _headerKey,
        refreshText: "下拉刷新",
        refreshReadyText: "释放刷新",
        refreshingText: "刷新...",
        refreshedText: "刷新完成",
        moreInfo: "更新时间 %T",
        bgColor: Colors.transparent,
        textColor: Colors.black87,
        moreInfoColor: Colors.black54,
        showMore: true,
      ),
      refreshFooter: ClassicsFooter(
        key: _footerKey,
        loadText: "上拉加载",
        loadReadyText: "释放加载",
        loadingText: "加载...",
        loadedText: "加载完成",
        noMoreText: "没有更多了...",
        moreInfo: "加载时间 %T",
        bgColor: Colors.transparent,
        textColor: Colors.black87,
        moreInfoColor: Colors.black54,
        showMore: true,
      ),
      child: ListView.separated(
          itemCount: _list.length,
          separatorBuilder: (BuildContext context, int index){
            return Divider();
          },
          itemBuilder: (BuildContext context, int index) {
            return Container(
              padding: EdgeInsets.all(8.0),
              child: Row(
                children: <Widget>[
                  _list[index].imageUrl==null?SizedBox(width: 0,):
                  Expanded(
                    flex: 1,
                    child: Image.network("https:" + _list[index].imageUrl),
                  ),
                 Expanded(
                   flex: 3,
                   child: Container(
                     padding: EdgeInsets.all(5.0),
                     child: Text(_list[index].title,maxLines: 3,overflow: TextOverflow.ellipsis,),
                   ),
                 ),
                ],
              ),
            );
          }),
    );
  }
}

class ToutiaoModel {
  final String title;
  final String imageUrl;
  ToutiaoModel(this.title, {this.imageUrl});
}
